package com.cs.beneficios.web.action;
import com.cs.beneficios.business.entity.ProgramaDAO;
import com.cs.beneficios.business.entity.SedeDAO;
import com.cs.beneficios.business.entity.SubProgramaDAO;
import com.cs.beneficios.business.entity.SubprogramaSedeDAO;
import com.cs.beneficios.business.model.ProgramaVO;
import com.cs.beneficios.business.model.SubProgramaVO;
import com.cs.beneficios.business.model.SubprogramaSedeVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.SQLException;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class BeneficiosSedeAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
  
    ActionMessages messages = new ActionMessages();
    try
    {
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        Object codePrograma =  (Object)request.getParameter("codePrograma");
        //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		ConnectionFactory cf = new ConnectionFactory();
        HttpSession session = request.getSession();
        UserVO user = (UserVO)session.getAttribute("userInfo");
        session.removeAttribute("msg");
        session.setAttribute("msg","");
        Collection programas=null;
        Collection subprogramas=null;
        Collection sedes=null;
        ProgramaDAO objProgramaDAO;
        SubProgramaDAO objSubProgramaDAO;
        SedeDAO  objSedeDAO;
        SubprogramaSedeDAO objSubsedeDAO;
		Object IdUbicacion = request.getParameter("IdUbicacion");
        
		if(IdUbicacion != null){
			request.setAttribute("IdUbicacion", IdUbicacion);
		}
		
        try
        {
          objSedeDAO = new SedeDAO(cf);
          sedes = objSedeDAO.GetSede();
          cf.closeConnection(objSedeDAO.getConn());
        }catch(SQLException e){
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSSPE - cwsub ********/");
        }
        if(sedes.size() > 0){
          session.setAttribute("sedes",sedes);
          /*if(codePrograma == null){ 
            //session.removeAttribute("programas");*/
            try
            {
              objProgramaDAO = new ProgramaDAO(cf);
              programas = objProgramaDAO.findProgramaWithoutSede(new ProgramaVO(),user.getCode(),user.getUserGroupName(),user.getCodeArea());
              cf.closeConnection(objProgramaDAO.getConn());
            }catch(SQLException e){
				System.err.println("/******** TDSUB - cwsub");
			   e.printStackTrace();
			   System.err.println("TDSSPE - cwsub ********/");
            }
            session.removeAttribute("msg");
            if(programas.size() > 0){
              session.setAttribute("programas",programas);
            }else
            {
              session.setAttribute("msg","No se encontraron programas vigentes a la fecha..");
            }
         // }
        
          if(codePrograma != null)
          {
            //session.removeAttribute("subprogramas");
            String codpro = (String)codePrograma;
            if(!codpro.equals("nulo"))
            {
              try
              {
                objSubProgramaDAO = new SubProgramaDAO(cf);
                SubProgramaVO subpro = new SubProgramaVO();
                subpro.setCodePrograma(new Long((String)codePrograma));
                subprogramas = objSubProgramaDAO.findSubPrograma(subpro,user.getCode(),user.getUserGroupName(),user.getCodeArea());
                cf.closeConnection(objSubProgramaDAO.getConn());
              }catch(SQLException e){
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSSPE - cwsub ********/");
              }
              session.removeAttribute("msg");
              if(subprogramas.size() > 0){
                session.setAttribute("subprogramas",subprogramas);
              }else
              {
                session.setAttribute("msg","No se encontraron subprogramas asociados a este programa que esten vigentes..");
              }
            }else{
                session.setAttribute("msg","");
                session.removeAttribute("subprogramas");
            }
          }
        }else
        {
          session.setAttribute("msg","No se encontraron sedes vigentes a la fecha..");
        }
        
        Object accion = request.getParameter("accion");
        Object codeSede = request.getParameter("code");
        Object codeSubprograma = request.getParameter("codeSubPrograma");
        Object desde = request.getParameter("desde");
        Object hasta = request.getParameter("hasta");
        Object cantidad = request.getParameter("cantidad");
        String codeSede1 = (String)codeSede;
        String codeSubprograma1 = (String)codeSubprograma;
        String codePrograma1 = (String)codePrograma;
        
        //Proceso para la auditoria
        String terminalAddress = request.getRemoteAddr();
        String strTerminal = ("WEB="+terminalAddress);
        Calendar c = Calendar.getInstance(); 
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");   
        //Fin del proceso
        String strPar[] = {user.getName(), dateFormat.format(c.getTime()),strTerminal,user.getName(), dateFormat.format(c.getTime()),strTerminal};
        if(accion != null)
        {
          String accion1 = (String)accion;
          if(!accion1.equals("BuscarTodo"))
          {
              if(!accion1.equals("BuscarSubprogrmas"))
              {
                  if(codeSede != null && codeSubprograma != null && desde != null && hasta != null && cantidad != null)
                  {
                    if(!codeSede.equals("nulo") && !codeSubprograma1.equals("nulo"))
                    {
                      try
                      {
                        objSubsedeDAO = new SubprogramaSedeDAO(cf);
                        String resultado[] = objSubsedeDAO.insertSubprogramaSede(
                                            new Long((String)codeSede),
                                            new Long((String)codeSubprograma),
                                            (String)desde,(String)hasta,(String)cantidad,strPar);
                        
                        if(resultado[0].equals("true"))
                        {
                          accion1 = "BuscarTodo";
                          session.setAttribute("msg","Se asigno correctamente el beneficio a la sede");
                          objSubsedeDAO.insertUsuarioSede(new Long(resultado[1]),user.getCode(),strPar);
                        }else
                        {
                          if(resultado[0].equals("ususede"))
                          {
                            objSubsedeDAO.insertUsuarioSede(new Long(resultado[1]),user.getCode(),strPar);
                            session.setAttribute("msg","Ese beneficio ya esta asignado a esa sede en ese periodo de tiempo.");
                          }else
                            session.setAttribute("msg","");
                        }
                        cf.closeConnection(objSubsedeDAO.getConn());
                      }catch(SQLException e)
                      {
						System.err.println("/******** TDSUB - cwsub");
						e.printStackTrace();
						System.err.println("TDSSPE - cwsub ********/");
                      }
                    }   
                  }
              }
          }
          
          session.removeAttribute("beneficiosSede");   
          if(accion1.equals("BuscarTodo"))
          {
              Collection beneficiosSede = null;
              try
              {
                SubprogramaSedeVO objSubsedeVO = new SubprogramaSedeVO();
                if(codeSede != null && !codeSede1.equals("nulo"))
                {
                  objSubsedeVO.setCodeSede(new Long((String)codeSede));
                }
                if(codePrograma != null && !codePrograma1.equals("nulo"))
                {
                  objSubsedeVO.setCodePrograma(new Long((String)codePrograma));
                }
                if(codeSubprograma != null && !codeSubprograma1.equals("nulo"))
                {
                  objSubsedeVO.setCodeSubprograma(new Long((String)codeSubprograma));
                }
                
                objSubsedeDAO = new SubprogramaSedeDAO(cf);
                beneficiosSede = objSubsedeDAO.getSubprogramaSede(objSubsedeVO);
                cf.closeConnection(objSubsedeDAO.getConn());
                if(beneficiosSede != null){
                  if(beneficiosSede.size() > 0)
                  {
                    session.setAttribute("beneficiosSede",beneficiosSede);   
                  }
                }
                objSubsedeVO = null;
              }catch(SQLException e)
              {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSSPE - cwsub ********/");
              }
          }
          
        }
    }catch (UserException ue) 
        {
         messages.add("msgWarn",  new ActionMessage("loginForm.message."
                                            + ue.getExceptionVO().getId()));
         saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
      
    }
    
    
    
    
    
    return mapping.findForward("success");
  }
}